"""
新闻管理API路由
演示复杂的查询和搜索功能
"""
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from sqlalchemy import desc, or_, and_

from ..database import get_db
from ..models.news import News
from ..models.user import User
from ..schemas.news import NewsCreate, NewsUpdate, NewsResponse, NewsListResponse
from ..dependencies import get_current_active_user


router = APIRouter(prefix="/api/news", tags=["新闻管理"])


@router.get("", response_model=NewsListResponse, summary="获取新闻列表")
async def get_news_list(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页数量"),
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    category: Optional[str] = Query(None, description="新闻分类"),
    published_only: bool = Query(True, description="只显示已发布的新闻"),
    featured_only: bool = Query(False, description="只显示置顶新闻"),
    db: Session = Depends(get_db)
):
    """
    获取新闻列表，支持搜索和筛选

    这个接口演示了：
    1. 复杂的查询条件组合
    2. 全文搜索（标题和摘要）
    3. 多种筛选条件
    4. 排序逻辑（置顶优先，然后按发布时间）
    """
    # 构建基础查询
    query = db.query(News)

    # 搜索关键词（在标题和摘要中搜索）
    if keyword:
        search_filter = or_(
            News.title.contains(keyword),
            News.excerpt.contains(keyword)
        )
        query = query.filter(search_filter)

    # 分类筛选
    if category:
        query = query.filter(News.category == category)

    # 只显示已发布的新闻
    if published_only:
        query = query.filter(News.is_published == True)

    # 只显示置顶新闻
    if featured_only:
        query = query.filter(News.is_featured == True)

    # 排序：置顶优先，然后按发布时间倒序
    query = query.order_by(desc(News.is_featured), desc(News.published_at))

    # 计算总数
    total = query.count()

    # 分页
    offset = (page - 1) * size
    items = query.offset(offset).limit(size).all()

    # 计算总页数
    pages = (total + size - 1) // size

    return NewsListResponse(
        items=items,
        total=total,
        page=page,
        size=size,
        pages=pages
    )


@router.get("/{news_id}", response_model=NewsResponse, summary="获取新闻详情")
async def get_news_detail(
    news_id: int,
    db: Session = Depends(get_db)
):
    """
    获取新闻详情并增加浏览次数

    Args:
        news_id: 新闻ID
        db: 数据库会话

    Returns:
        NewsResponse: 新闻详情
    """
    news = db.query(News).filter(News.id == news_id).first()

    if not news:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="新闻不存在"
        )

    # 增加浏览次数
    news.view_count += 1
    db.commit()
    db.refresh(news)

    return news


@router.post("", response_model=NewsResponse, summary="创建新闻")
async def create_news(
    news_data: NewsCreate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    创建新闻

    需要管理员权限
    """
    # 创建新闻对象
    db_news = News(**news_data.dict())

    # 保存到数据库
    db.add(db_news)
    db.commit()
    db.refresh(db_news)

    return db_news


@router.put("/{news_id}", response_model=NewsResponse, summary="更新新闻")
async def update_news(
    news_id: int,
    news_data: NewsUpdate,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    更新新闻信息

    需要管理员权限
    """
    # 查找新闻
    db_news = db.query(News).filter(News.id == news_id).first()

    if not db_news:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="新闻不存在"
        )

    # 更新字段
    update_data = news_data.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(db_news, field, value)

    # 保存更改
    db.commit()
    db.refresh(db_news)

    return db_news


@router.delete("/{news_id}", summary="删除新闻")
async def delete_news(
    news_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    删除新闻

    需要管理员权限
    """
    # 查找新闻
    db_news = db.query(News).filter(News.id == news_id).first()

    if not db_news:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="新闻不存在"
        )

    # 删除新闻
    db.delete(db_news)
    db.commit()

    return {"message": "新闻删除成功"}